package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.ActivitySubscribeAppId;
import com.youlu.campus.entity.VO.req.ActivitySubscribeAppIdQueryVO;
import com.youlu.campus.entity.WechatConfigInfo;
import com.youlu.campus.service.activity.ActivitySubscribeAppIdService;
import com.youlu.campus.service.wechat.WechatConfigInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class ActivitySubscribeAppIdServiceImpl implements ActivitySubscribeAppIdService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WechatConfigInfoService wechatConfigInfoService;

    @Override
    public Page<ActivitySubscribeAppId> list(ActivitySubscribeAppIdQueryVO req) {
        log.info(":>>> 开始获取活动积分配置:{}", JSON.toJSONString(req));
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(req.getActivityId()));
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            query.addCriteria(Criteria.where("appId").is(req.getAppId()));
        }
        if (Objects.nonNull(req.getStatus())) {
            query.addCriteria(Criteria.where("status").is(req.getStatus()));
        }
        query.addCriteria(Criteria.where("deleted").ne(true));
        long count = mongoTemplate.count(query, ActivitySubscribeAppId.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivitySubscribeAppId> infos = mongoTemplate.find(query.with(pageRequest), ActivitySubscribeAppId.class);
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);

    }

    @Override
    public boolean create(@NotNull ActivitySubscribeAppId req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req.setStatus(true);
        if (StringUtils.isNotBlank(req.getAppId())) {
            WechatConfigInfo configInfo = wechatConfigInfoService.find(req.getAppId());
            if (Objects.nonNull(configInfo)) {
                req.setAppName(configInfo.getName());
            }
        }
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(@NotNull ActivitySubscribeAppId req) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        boolean toUpate = false;
        if (StringUtils.isNotBlank(req.getActivityId())) {
            update.set("activityId", req.getActivityId());
            toUpate = true;
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            update.set("appId", req.getAppId());
            if (StringUtils.isNotBlank(req.getAppId())) {
                WechatConfigInfo configInfo = wechatConfigInfoService.find(req.getAppId());
                if (Objects.nonNull(configInfo)) {
                    update.set("appName", configInfo.getName());
                }
            }
        }
        if (StringUtils.isNotBlank(req.getDesc())) {
            update.set("desc", req.getDesc());
        }
        if (Objects.nonNull(req.getStatus())) {
            update.set("status", req.getStatus());
        }
        if (toUpate) {
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ActivitySubscribeAppId.class);
            return updateResult.getModifiedCount() > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean delete(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, ActivitySubscribeAppId.class);
        return deleteResult.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public String getActivitySubscribeAppIdByActivityId(String activityId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        List<ActivitySubscribeAppId> list = this.mongoTemplate.find(query, ActivitySubscribeAppId.class);
        if(CollectionUtils.isEmpty(list)){
            return "";
        }
        ActivitySubscribeAppId activitySubscribe = list.stream().filter(activitySubscribeAppId -> Boolean.TRUE.equals(activitySubscribeAppId.getStatus())).findFirst().orElse(null);
        if(Objects.isNull(activitySubscribe)){
            return "";
        }
        log.info("活动:{}报名订阅公众号appId:{}",activityId,activitySubscribe.getAppId());
        return activitySubscribe.getAppId();
    }
}
